import md5 from 'md5'
import type { InternalAxiosRequestConfig } from 'axios'
import { setCookie, getUrlQuery, useUserStore } from '@/utils'

/**
 * 传入一个对象和布尔值，return根据ASCII码升序或者降序的对象
 * isSort: true代表升序，false代表降序
 * */
export const sortASCII = (obj: Record<string, any>, isSort: boolean) => {
  const arr: any[] = []
  Object.keys(obj).forEach((item) => arr.push(item))

  const sortArr = isSort ? arr.sort() : arr.sort().reverse()
  const sortObj: Record<string, any> = {}

  sortArr.forEach((key) => {
    if (obj[key] !== null && typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
      // Recursive call if the value is an object (not including arrays)
      sortObj[key] = sortASCII(obj[key], isSort)
    } else {
      sortObj[key] = obj[key]
    }
  })

  return sortObj
}

// 过滤空字段
function filter(obj?: any) {
  for (const [key, val] of Object.entries(obj)) {
    if (val == null || val == undefined || (typeof val == 'number' && isNaN(val))) {
      delete obj[key]
    }
    if (obj[key] !== null && typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
      filter(obj[key])
    }
  }
}

// 请求头sk
export function setHeaderSK(config: any = {}) {
  let { skToken, memberCode, channelCode }: any = getUrlQuery() || {}
  let params = (config.method.toLowerCase() == 'get' ? config.params : config.data) || {}
  filter(params)
  params['ts'] = new Date().getTime()
  params['_random'] = String(Math.random()).slice(2, 12)
  params = sortASCII(params, true)

  if (config.method.toLowerCase() == 'get') {
    config.params = params
    // get验签台号要求
    Object.keys(params).map((key) => {
      if (typeof params[key] == 'number') params[key] = String(params[key])
    })
    config.headers['sk'] = md5(JSON.stringify(params))
  } else {
    config.data = params
    config.headers['sk'] = md5(JSON.stringify(params))
  }

  // 设置skToken
  if (skToken) {
    skToken = `${skToken}_${memberCode}`
  } else {
    const userInfo: any = useUserStore().userInfo
    skToken = userInfo['skToken'] || localStorage.getItem(`skToken_${channelCode}_${memberCode}`)
  }
  config.headers['skToken'] = skToken
  setCookie('memberCode', memberCode)
  return config
}

// 设置登录信息
export function setHeaderLoginQuery(config: InternalAxiosRequestConfig) {
  const { memberCode, channelCode } = getUrlQuery() || {}

  const { method, data, params, url } = config

  const targetData = method!.toLowerCase() == 'get' ? params : data

  let newConfig: any = { memberCode, channelCode }

  // 新版接口有版本号，兼容老版请求
  if (/\/v[3-9]+/gim.test(url!)) {
    newConfig.data = {
      memberCode,
      channelCode,
      ...targetData,
    }
  } else {
    newConfig = Object.assign(targetData, newConfig)
  }

  const type: 'params' | 'data' = method!.toLowerCase() == 'get' ? 'params' : ('data' as 'data')

  config[type] = newConfig
}
